package services;

import java.util.Collection;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import domain.Administrator;
import domain.Challenge;
import domain.Event;

import repositories.ChallengeRepository;

@Service
@Transactional
public class ChallengeService {
	
	// Managed repository -----------------------------------------------------
	
			@Autowired
			private ChallengeRepository challengeRepository;

			@Autowired
			private AdministratorService administratorService;
			
			// Constructors -----------------------------------------------------------

			public ChallengeService() {
				super();
			}
			
			// Simple CRUD methods ----------------------------------------------------
			
			public Challenge create(Event e) {
				Administrator a = administratorService.findByPrincipal();
				Challenge c = new Challenge();
				c.setAdministrator(a);
				c.setEvent(e);
				return c;
			}
			
			public void save(Challenge c) {
				Assert.notNull(c);
				Assert.isTrue(c.getAdministrator().equals(administratorService.findByPrincipal()));
				Assert.isTrue(c.getEvent().getStartMoment().compareTo(new Date())>0);
				challengeRepository.save(c);
			}
			
			public void delete(Challenge c){
				Assert.notNull(c);
				Assert.isTrue(c.getAdministrator().equals(administratorService.findByPrincipal()));
				Assert.isTrue(c.getEvent().getStartMoment().compareTo(new Date())>0);
				challengeRepository.delete(c);
			}

			// Other business methods -------------------------------------------------

			public Collection<Challenge> findChallengesByEvent(Event event){
				return challengeRepository.findChallengesByEvent(event.getId());
			}
}
